
import * as utc from "../util/utc.js";
import {newProduct, resolveValidTime} from "./productUtils.js";
import {tr} from "../ux/translations.js";
import * as sources from "./sources.js";
import {buildFlatProduct} from "./flatProduct.js";
import {ø} from "../util/objects.js";
import {createUnitDescriptors} from "../util/units.js";
import {gaiaPath} from "./gaia.js";
import {createAuroraPalette} from "../palette/aurora.js";


let palette;

function ovationPath(attr) {
    const {time_cursor} = attr;
    const validTime = resolveValidTime(time_cursor, {minute: 5});
    const dir = time_cursor === "current" ? "current" : utc.print(validTime, "{YYYY}/{MM}/{DD}");
    const stamp = time_cursor === "current" ? "current" : utc.print(validTime, "{YYYY}{MM}{DD}{hh}{mm}");
    const file = `${stamp}-ovation.json`;
    return gaiaPath("data/ovation", dir, file);
}

export function createAuroraLayer(attr) {
    // HACK: Because some time slots will be filled by older data (since the data source is not reliable),
    // we want to use the time_cursor as the basis of navigation rather than the valid time of the downloaded
    // data. The validTime() method is replaced by flatProduct to use the data's valid time, so this
    // const can be used to avoid that.
    const attrValidTime = resolveValidTime(attr.time_cursor, {minute: 5});
    const stepper = step => function() {
        return resolveValidTime(utc.add(attrValidTime, step), {minute: 5});
    };

    return ø(newProduct(), {
        type: "aurora",
        descriptionHTML: {
            name: tr`Probability of Visible Aurora`,
            qualifier: "",
        },
        sourceHTML: sources.ovation,
        paths: [ovationPath(attr)],
        validTime: () => ø(attrValidTime),
        prev2: stepper({hour:  -1}),
        prev1: stepper({minute: -5}),
        next1: stepper({minute: +5}),
        next2: stepper({hour:  +1}),
        navLabels: {
            prev2: `-1 ${tr`hour`}`,
            prev1: `-5 ${tr`minutes`}`,
            next1: `+5 ${tr`minutes`}`,
            next2: `+1 ${tr`hour`}`,
        },
        builder: file => {
            file.has_missing ??= false;
            return buildFlatProduct(file);
        },
        unitDescriptors: createUnitDescriptors({
            "%": {html: tr`% Visibility Chance`, convert: x => x, precision: 0},
        }),
        alpha: {single: 160, animated: 140},
        scale: palette ??= createAuroraPalette(),
    });
}
